package com.zhl.media.app.mvp.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.LogUtils;
import com.muddzdev.styleabletoast.StyleableToast;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.header.FlyRefreshHeader;
import com.scwang.smartrefresh.header.StoreHouseHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhl.media.app.R;
import com.zhl.media.app.di.component.DaggerWorkTaskComponent;
import com.zhl.media.app.di.module.WorkTaskModule;
import com.zhl.media.app.greendao.AdJustDao;
import com.zhl.media.app.greendao.ElevatorDao;
import com.zhl.media.app.greendao.MediaPositionDao;
import com.zhl.media.app.greendao.ProjDao;
import com.zhl.media.app.model.MediaPosition;
import com.zhl.media.app.model.Node;
import com.zhl.media.app.model.OffLineData;
import com.zhl.media.app.model.Proj;
import com.zhl.media.app.mvp.adapter.TreeListViewAdapter;
import com.zhl.media.app.mvp.adapter.WorkTaskTreeAdapter;
import com.zhl.media.app.mvp.contract.WorkTaskContract;
import com.zhl.media.app.mvp.presenter.WorkTaskPresenter;
import com.zhl.media.app.mvp.ui.activity.PreviewActivity;
import com.zhl.media.app.utils.ApkHelper;
import com.zhl.media.app.utils.EntityManager;
import com.zhl.media.commonres.base.AppFragment;
import com.zhl.media.commonres.dialog.UpdataDialog;
import com.zhl.media.commonres.view.EmptyLayout;
import com.zhl.media.commonsdk.core.EventBusCode;
import com.zhl.media.commonsdk.core.RouterHub;
import com.zhl.media.commonsdk.data.UserUtil;
import com.zhl.media.commonsdk.utils.VersionUtils;

import org.simple.eventbus.Subscriber;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

import static android.app.Activity.RESULT_OK;
import static com.zhl.media.app.mvp.model.api.Api.APP_DOMAIN;

public class WorkTaskFragment extends AppFragment<WorkTaskPresenter> implements WorkTaskContract.View{

    List<Proj> mDatas;
    @BindView(R.id.task_list)
    ListView listView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.emptyLayout)
    EmptyLayout emptyLayout;

    private WorkTaskTreeAdapter mAdapter;
    private String date;
    private ProjDao projDao;
    private Handler handler = new Handler(Looper.getMainLooper());
    private UpdataDialog updataDialog;
    private File apkFile;
    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerWorkTaskComponent.builder().appComponent(appComponent).workTaskModule(new WorkTaskModule(this)).build().inject(this);
    }
    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.work_task_fragment, container, false);
        return view;
    }
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        date = Hawk.get("thisDate","0");
        projDao = EntityManager.getInstance(getActivity()).getProjDao();
        refreshLayout.setEnableLoadMore(false);
        mDatas = new ArrayList<Proj>();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout1) {
                if(!date.equals("0")){
                    refreshOffLineData();
                }else {
                    emptyLayout.bindView(refreshLayout);
                    emptyLayout.showEmpty("~暂时未获取本期日期~");
                    refreshLayout.finishRefresh();
                }
            }
        });
        if(EntityManager.getInstance(getActivity()).getProjDao().loadAll().size()==0){
            if(EntityManager.getInstance(getActivity()).getMediaPhotoDao().loadAll().size()==0){
                refreshLayout.autoRefresh();
            }else {
                loadData();
            }
        }else {
            loadData();
        }
        mPresenter.checkupdate();
    }

    private void refreshOffLineData(){
        if(EntityManager.getInstance(getActivity()).getMediaPhotoDao().loadAll().size()==0 && !UserUtil.getAdjust()){
            mPresenter.getNetWorkListProj(date);
        }else {
            StyleableToast.makeText(getActivity(), "必须上传上刊结果和调整结果才可更新最新数据", Toast.LENGTH_LONG, R.style.mytoast).show();
            refreshLayout.finishRefresh();
        }
    }

    public int getScrollY() {
        View c = listView.getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight() ;
    }


    private void loadData(){
        List<Proj> projs = projDao.loadAll();
        try {
            mAdapter = new WorkTaskTreeAdapter(listView, getActivity(), projs, 1);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        listView.setAdapter(mAdapter);
//        listView.setSelection(Hawk.get("listPostion",0));
        if(projs.size()<=2){
            emptyLayout.bindView(listView);
            emptyLayout.showEmpty("~暂无任何楼盘~");
        }else {
            emptyLayout.hideEmpty();
        }
        mAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
            @Override
            public void onClick(Node node, int position) {
//                if(node.getLevel()==1 || node.getLevel() == 2){
//                    Proj item = projDao.queryBuilder().where(ProjDao.Properties.Id.eq(node.getId())).unique();
//                    if(item.getIsExpand()==false){
//                        item.setIsExpand(true);
//                    }else {
//                        if(node.getLevel()==1){
//                            List<Proj> list = projDao.queryBuilder().where(ProjDao.Properties.ProjectId.eq(node.getId())).list();
//                            for (Proj p: list) {
//                                p.setIsExpand(false);
//                            }
//                            projDao.updateInTx(list);
//                        }
//                        item.setIsExpand(false);
//                    }
//                    projDao.update(item);
//                }
                if (node.getLevel() == 3){
//                    Hawk.put("listPostion",getScrollY());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("proj",node);
                    ARouter.getInstance().build(RouterHub.APP_MEDIAACTIVITY).with(bundle).navigation();
                }
            }
        });
    }
    @Override
    public void setData(@Nullable Object data) {
        loadData();
    }
    public static WorkTaskFragment newInstance() {
        Bundle args = new Bundle();
        WorkTaskFragment fragment = new WorkTaskFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Subscriber(tag = "update_off_line_data")
    public void update_off_line_data(int code) {
        if(code == EventBusCode.OFFLINEDATA){
            refreshOffLineData();
        }
    }

    // 更新列表结果
    @Subscriber(tag = "update_gzrelist")
    public void updateDsc(int code) {
        if(code == EventBusCode.GZRELIST){
            loadData();
        }
    }

    @Override
    public void showLoading() {

    }
    @Override
    public void hideLoading() {
        refreshLayout.finishRefresh();
    }

    @Override
    public void showMessage(@NonNull String message) {

    }
    @Override
    public void launchActivity(@NonNull Intent intent) {

    }
    @Override
    public void killMyself() {

    }

    @Override
    public void onOffLineData(OffLineData data) {
        try {
            MediaPositionDao mediaPositionDao = EntityManager.getInstance(getActivity()).getMediaPositionDao();
            ElevatorDao elevatorDao = EntityManager.getInstance(getActivity()).getElevatorDao();
            AdJustDao adJustDao = EntityManager.getInstance(getActivity()).getAdJustDao();
            projDao.deleteAll();
            mediaPositionDao.deleteAll();
            elevatorDao.deleteAll();
            adJustDao.deleteAll();
            projDao.insertInTx(data.getProjects());
            mediaPositionDao.insertInTx(data.getMedias());
            elevatorDao.insertInTx(data.getElevators());
            adJustDao.insertInTx(data.getAdJusts());
            UserUtil.setAdjust(false);
            loadData();
        }catch (Exception e){
            AlertDialog.Builder builder  = new AlertDialog.Builder(getActivity());
            builder.setTitle("异常提示" );
            builder.setMessage(e.toString());
            builder.setPositiveButton("取消" ,  null );
            builder.show();
        }
    }

    @Override
    public void checkUpdate(Map data) {
        if (VersionUtils.getVersionCode(getActivity())<(Double)data.get("packageCode")) {
            updataDialog = new UpdataDialog(getActivity(), "发现新版本," + (String) data.get("versionNo") + "来啦", (String) data.get("updateContent"));
            updataDialog.show();
            updataDialog.setOnCenterItemClickListener(new UpdataDialog.OnCenterItemClickListener() {
                @Override
                public void OnCenterItemClick(UpdataDialog dialog, View view) {
                    updataDialog.l();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        RxPermissions rxPermission = new RxPermissions(getActivity());
                        rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Permission>() {
                            @Override
                            public void accept(Permission permission) throws Exception {
                                if (permission.granted) {
                                    updateApk(APP_DOMAIN + "file/downloadApk/" + data.get("fileId"));
                                } else if (permission.shouldShowRequestPermissionRationale) {
                                    StyleableToast.makeText(getActivity(), "必须打开权限!", Toast.LENGTH_LONG, R.style.mytoast).show();
                                } else {
                                    StyleableToast.makeText(getActivity(), "必须打开权限!", Toast.LENGTH_LONG, R.style.mytoast).show();
                                }
                            }
                        });
                    }else {
                        updateApk(APP_DOMAIN + "file/downloadApk/" + data.get("fileId"));
                    }
                }
            });
        }
    }

    //升級apk
    private void updateApk(String url) {
        ApkHelper.downApk(url, new ApkHelper.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                apkFile = file;
                if (Build.VERSION.SDK_INT >= 26) {
                    //来判断应用是否有权限安装apk
                    boolean installAllowed= getActivity().getPackageManager().canRequestPackageInstalls();
                    //有权限
                    if (installAllowed) {
                        //安装apk
                        publicApk(file);
                    } else {
                        //将用户引导至安装未知应用界面。
                        Uri packageURI = Uri.parse("package:" + getActivity().getPackageName());
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                        startActivityForResult(intent, 10086);
                    }
                } else {
                    publicApk(file);
                }
            }
            @Override
            public void onDownloading(final int progress) {
                if(progress != 100) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            updataDialog.setButtonText("正在下载安装包" + progress + "%");
                        }
                    });
                }else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            updataDialog.setButtonText("下载完成,去安装");
                        }
                    });
                }
            }
            @Override
            public void onDownloadFailed(Exception e) {

            }
        });
    }

    private void publicApk(File pFile){
        install(pFile);
        updataDialog.setDownloadOkClick();
        updataDialog.setOnDownloadOkClickListener(new UpdataDialog.OnDownloadOkClickListener() {
            @Override
            public void OnClick() {
                install(pFile);
            }
        });
    }

    private void install(File file){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        } else {
            Uri uri = getUriFromFile(getActivity(), file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".fileprovider", file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086 &&  resultCode == RESULT_OK) {
            publicApk(apkFile);
        }
    }
}
